import { Component, OnInit, TemplateRef } from '@angular/core';
import { ClassService } from '../../services/class.service';
import { TermService } from '../../services/term.service';
import { CourseService } from '../../services/course.service';
import { Term } from '../Interfaces/Term';
import { Course } from '../Interfaces/Course';
import { ClassEntity, Search } from '../Interfaces/ClassEntity';
import { Page } from '../Interfaces/Page';

import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

import { BsDatepickerConfig, BsLocaleService } from 'ngx-bootstrap/datepicker';
import { DateFormatter } from 'ngx-bootstrap/datepicker/date-formatter';

@Component({
  selector: 'app-class',
  templateUrl: './class.components.html',
  styles: []
})
export class ClassComponent implements OnInit {

    search: Search = new Search();

    classEntities: ClassEntity[];
    classEntity: ClassEntity = new ClassEntity();
    addModalRef: BsModalRef;
    editModalRef: BsModalRef;
    deleteModalRef: BsModalRef;
    rotate = false;
    maxSize = 10;
    page: Page = new Page();


    courses: Course[];
    terms: Term[];
    allTerms: Term[];
    daterange: any[];
    timeRange: number[] = [];
    timeRange1: number[] = [];
      // 时间空间语言设置
    locale = 'zh-cn';
    // search = new Search();
    constructor(
        private _localeService: BsLocaleService,
        private modalService: BsModalService,
        private classService: ClassService,
        private termService: TermService,
        private courseService: CourseService
    ) {
        // this.pageInit();
        this._localeService.use(this.locale);
        // this.modalService.onHidden.subscribe(res => { this.getClassEntities(); } );
    }

    ngOnInit() {
        this.getClassEntities();
        this.getAllTerms();
    }


    pageInit() {
        this.getCourses();
        this.getTerms();
        this.generateTimeRange();
    }
    getCourses() {
        this.courseService.getCourses().subscribe(res => {
            this.courses = res.data as Course[];
            console.log(this.courses);
        });
    }

    getTerms() {
        this.termService.getTerms().then(res => {
            this.terms = res;
        });
    }

    generateTimeRange() {
        for (let i = 1; i <= 24 ; i++) {
            this.timeRange.push(i);
            this.timeRange1.push(i);
        }
    }


    addClassEntity() {
        this.addModalRef.hide();
        const format = new DateFormatter();
        this.classEntity.start_end = this.classEntity.start_time + '-' + this.classEntity.end_time;
        this.classEntity.start_day = format.format(this.daterange[0], 'YYYY-MM-DD', 'en');
        this.classEntity.end_day = format.format(this.daterange[1], 'YYYY-MM-DD', 'en');
        this.classEntity.course_id = 0;
        console.log(this.classEntity);
        this.classService.addClassEntity(this.classEntity).subscribe(res => {
            if (!res.errors) {
                alert('添加成功');
                this.getClassEntities();
            } else {
                alert('添加失败！');
            }
        });
    }

    editClassEntity() {
        this.editModalRef.hide();
        const format = new DateFormatter();
        this.classEntity.start_end = this.classEntity.start_time + '-' + this.classEntity.end_time;
        this.classEntity.start_day = format.format(this.daterange[0], 'YYYY-MM-DD', 'en');
        this.classEntity.end_day = format.format(this.daterange[1], 'YYYY-MM-DD', 'en');
        this.classService.editClassEntity(this.classEntity).subscribe(res => {
            if (!res.errors) {
                alert('修改成功');
                this.getClassEntities();
            } else {
                alert('修改失败！');
            }
        });
    }


    getClassEntities() {
        this.classService.getClassEntities().subscribe(
            res => {
                this.classEntities = res.data.data as ClassEntity[];
                this.page.currentPage = res.data.current_page;
                this.page.total = res.data.total;
                this.page.perPage = res.data.per_page;
            }
        );
    }

    getAllTerms() {
        this.termService.getTerms().then(res => {
            this.allTerms = res as Term[];
        });
    }


      // 条件查询
      searchClassEntity() {
        if (!this.search) {
            return false;
        } else {
            this.classService.getClassEntitiesByCondition(this.search).subscribe(res => {
                this.classEntities = res.data.data as ClassEntity[];
                this.page.currentPage = res.data.current_page;
                this.page.total = res.data.total;
                this.page.perPage = res.data.per_page;
            });
        }

    }

    // TODO 分页没做
    pageChanged(event) {
        console.log('Page changed to: ' + event.page);
        console.log('Number items per page: ' + event.itemsPerPage);
        this.search.page = event.page;
        this.classService.getClassEntitiesByCondition(this.search).subscribe(
            res => {
                this.classEntities = res.data.data as ClassEntity[];
                this.page.currentPage = res.data.current_page;
                this.page.total = res.data.total;
                this.page.perPage = res.data.per_page;
            }
        );
    }


    openAddModal(template: TemplateRef<any>) {
        this.classEntity = new ClassEntity();
        this.pageInit();
        this.addModalRef = this.modalService.show(
            template,
            Object.assign({}, {}, { class: 'gray modal-lg' })
        );
        // this.addModalRef.content.title = '新增班级';
        // this.addModalRef.content.classEntity = new ClassEntity();
    }

    openEditModal(template: TemplateRef<any>, item: ClassEntity) {
        // this.classEntity = new ClassEntity();
        this.pageInit();
        this.classEntity = JSON.parse(JSON.stringify(item));
        console.log(this.classEntity);
        this.daterange = [
            new Date(this.classEntity.start_day),
            new Date(this.classEntity.end_day)
        ];
        this.editModalRef = this.modalService.show(
            template,
            Object.assign({}, {}, { class: 'gray modal-lg' })
        );
        // this.editModalRef.content.title = '编辑班级' ;
        // this.editModalRef.content.classEntity = item;
    }

    deleteClassEntity(item: ClassEntity) {
        if (confirm('确认删除么?')) {
            this.classService.deleteClassEntity(item).subscribe(res => {
                if (!res.errors) {
                    alert('删除成功');
                    this.getClassEntities();
                } else {
                    alert('删除失败！');
                }
            });
        }
    }
}



// 新增弹出框
@Component({
    selector: 'app-new-modal',
    template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">{{title}}</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>

    <div class="modal-body">
      <form #addForm="ngForm" (submit)="addClassEntity()">
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">班级名称</label>
            <div class="col-sm-9">
                <input type="text"
                *ngIf="classEntity"
                required
                class="form-control"
                name="name"
                [(ngModel)]="classEntity.name"
                placeholder="如：蛙泳早班课1班"
                #uname="ngModel"
                >
            </div>
        </div>
        <!-- 学期 -->
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">学期</label>
            <div class="col-sm-9">
                <select
                required
                *ngIf="classEntity"
                class="form-control"
                name="term_id"
                [(ngModel)]="classEntity.term_id"
                #uterm_id="ngModel"
                >
                    <option>请选择学期</option>
                    <option
                        *ngFor="let item of terms"
                        value="{{item.id}}"
                    >{{ item.name }}</option>
                </select>
            </div>
        </div>
        <!-- 课程 -->
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">课程</label>
            <div class="col-sm-9">
                <select
                required
                *ngIf="classEntity"
                class="form-control"
                name="course_id"
                [(ngModel)]="classEntity.course_id"
                #ucourse_id="ngModel"
                >
                    <option>请选择课程</option>
                    <option
                        *ngFor="let item of courses"
                        value="{{ item.id }}"
                    >{{ item.name }}</option>
                </select>
            </div>
        </div>

        <!-- 开班日期区间 -->
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">开班日期区间</label>
            <div class="col-sm-9">
                <input
                    class="form-control"
                    #dpr="bsDaterangepicker"
                    *ngIf="classEntity"
                    bsDaterangepicker
                    name="daterange"
                    #urange="ngModel"
                    [(ngModel)]="daterange"
                    [bsConfig]="{ dateInputFormat: 'YYYY-MM-DD' }"
                >
            </div>
        </div>

        <!-- 开始时间 -->
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">每日开始时间</label>
            <div class="col-sm-9">
                <select
                required
                *ngIf="classEntity"
                class="form-control"
                name="start_time"
                [(ngModel)]="classEntity.start_time"
                #ustart_time="ngModel"
                >
                    <option
                        *ngFor="let item of timeRange"
                        value="{{ item}}"
                    >{{ item }}</option>
                </select>
            </div>
        </div>

        <!-- 结束时间 -->
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">每日结束时间</label>
            <div class="col-sm-9">
                <select
                required
                *ngIf="classEntity"
                class="form-control"
                name="start_time"
                [(ngModel)]="classEntity.end_time"
                #uend_time="ngModel"
                >
                    <option
                        *ngFor="let item of timeRange"
                        value="{{ item}}"
                    >{{ item }}</option>
                </select>
            </div>
        </div>

        <!-- 人数限制 -->
        <div class="form-group row">
            <label for="name" class="col-sm-3 col-form-label">人数限制</label>
            <div class="col-sm-9">
                <input type="number"
                *ngIf="classEntity"
                required
                class="form-control"
                name="member_limit"
                [(ngModel)]="classEntity.member_limit"
                placeholder="写数字"
                #umember_limit="ngModel"
                >
            </div>
        </div>

        <div class="form-group row">
            <div class="col-sm-2">
                <button type="submit" [disabled]="!addForm.form.valid" class="btn btn-success" >保存</button>
            </div>
        </div>
      </form>
    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">关闭</button>
    </div>
    `,
})

export class ClassAddModalComponent {
    title: string;
    courses: Course[];
    terms: Term[];
    classEntity: ClassEntity;
    daterange: any[];
    timeRange: number[] = [];
      // 时间空间语言设置
    locale = 'zh-cn';

    constructor(
        private _localeService: BsLocaleService,
        public bsModalRef: BsModalRef,
        private  courseService: CourseService,
        private termService: TermService,
        private classService: ClassService
    ) {
        this.pageInit();
        this._localeService.use(this.locale);
    }

    pageInit() {
        this.getCourses();
        this.getTerms();
        this.generateTimeRange();
    }
    getCourses() {
        this.courseService.getCourses().subscribe(res => {
            this.courses = res.data as Course[];
            console.log(this.courses);
        });
    }

    getTerms() {
        this.termService.getTerms().then(res => {
            this.terms = res;
        });
    }

    generateTimeRange() {
        for (let i = 1; i <= 24 ; i++) {
            this.timeRange.push(i);
        }
    }


    addClassEntity() {
        const format = new DateFormatter();
        this.classEntity.start_day = format.format(this.daterange[0], 'YYYY-MM-DD', 'en');
        this.classEntity.end_day = format.format(this.daterange[1], 'YYYY-MM-DD', 'en');
        this.classService.addClassEntity(this.classEntity).subscribe(res => {
            if (!res.errors) {
                alert('添加成功');
            } else {
                alert('添加失败！');
            }
        });
    }
}
